

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// youch lib
const Youch = require('youch');

// RSS
const RSS = require("./rss");
RSS.run();


// 拦截器
var loginInterceptor = require('./interceptor/login-interceptor');

// 路由器
var indexRouter = require('./routes/index');
var uploadRouter = require('./routes/upload');
var toolRouter = require('./routes/tool');
var otherRouter = require('./routes/other');
var userRouter = require('./routes/user');
var avatarRouter = require('./routes/avatar');
var articleRouter = require('./routes/article');
var wxRouter = require('./routes/wx');
var androidRouter = require('./routes/android');
var pagesRouter = require('./routes/pages');
var resourceRouter = require('./routes/resource');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json({ limit:"5MB" }));
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



app.all('*', function (req, res, next) {
	// res.header("Access-Control-Allow-Origin", "*");
	if (req.headers.host.includes("cyue.net") || req.headers.host.includes("cyue.site"))
		res.header("Access-Control-Allow-Origin", req.headers.origin);
	next();
});


// 拦截器
app.use('/api', loginInterceptor);


// 路由
app.use('/api', indexRouter);
app.use('/api', uploadRouter);
app.use('/api', toolRouter);
app.use('/api', otherRouter);
app.use('/api', userRouter);
app.use('/api', avatarRouter);
app.use('/api', articleRouter);
app.use('/api', wxRouter);
app.use('/api', androidRouter);
app.use(RSS.router);
app.use(pagesRouter);
app.use(resourceRouter);


// catch 404 and forward to error handler


// production
if (process.env.NODE_ENV === "production")
{
	app.use(function(_req, res, _next) {
		res.status(404).render("message", {
			title: "404",
			message: "Sorry can't find that!"
		});
	});
}
// development
else
{
	app.use(function(_req, _res, next) {
		next(createError(404));
	});
}



// error handler
app.use(async function(err, req, res, _next) {
	// set locals, only providing error in development
	res.locals.message = err.message;
	res.locals.error = req.app.get('env') === 'development' ? err : {};

	// PERFORM SOME ACTION
	if (req.app.get('env') === 'development' && err) {
		const youch = new Youch(err, req)
		const html = await youch.toHTML()

		res.writeHead(200, {'content-type': 'text/html'})
		res.write(html)
		res.end()
		return;
	}


	// render the error page
	res.status(err.status || 500);
	res.render('error');
});

module.exports = app;


